package com.lagou.edu.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 当前线程绑定唯一数据库连接
 */
public class ConnectionUtils {

    //存储当前线程的数据库连接
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /* 创建对象交给Ioc容器
    //构造方法私有化,外界无法实例化
    private ConnectionUtils() {
    }

    private static ConnectionUtils connectionUtils = new ConnectionUtils();

    //单例模式,对外提供获取实例化对象的接口
    public static ConnectionUtils getInstance() {
        return connectionUtils;
    }*/

    //初始化
    public void init() {
        System.out.println("执行初始化方法........");
    }

    //销毁
    public void destroy() {
        System.out.println("执行销毁方法........");
    }

    /**
     * 从当前线程获取唯一数据库连接
     *
     * @return
     */
    public Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null) {
            //当前线程连接为空,获取一个新连接
            connection = DruidUtils.getInstance().getConnection();
            //设置到当前线程中
            threadLocal.set(connection);

        }
        return connection;
    }
}
